package com.zyf.springboot.config.shiro;

//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zyf.springboot.entity.LoginUser;
//import com.zyf.springboot.entity.User;
//import com.zyf.springboot.mapper.UserMapper;
//import com.zyf.springboot.service.impl.UserServiceImpl;
import com.zyf.springboot.entity.User;
import com.zyf.springboot.mapper.UserMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import javax.annotation.Resources;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class MyRealm extends AuthorizingRealm {
    @Resource
    UserMapper userMapper;
    /*
    授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("username",username);
        User user = userMapper.selectOne(queryWrapper);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        Set set=new HashSet();
        set.add(username);
        System.out.println("<===========授权==========>");
        System.out.println("角色"+username);
        info.setRoles(set);
        info.setStringPermissions(null);
        return info;
    }

    /*
    认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("=======认证======");

        //从传过来的token获取到的用户名
        String principal = (String) authenticationToken.getPrincipal();
        System.out.println("用户名" + principal);

//        //假设是从数据库获得的 用户名，密码
//        LoginUser loginUser=new LoginUser("admin","111");
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("username",principal);
        User user = userMapper.selectOne(queryWrapper);
        if (user==null){
            return null;
        }

        if (user.getUsername().equals(principal)) {
//            SimpleAuthenticationInfo simpleAuthenticationInfo =
            return new SimpleAuthenticationInfo(principal, user.getPassword(), this.getName());
        }

        return null;

    }
}
